#include "Net.h"
static Net* m_instance = NULL;

Net::Net(void)
{
	callbackMap = CCDictionary::create();
	callbackMap->retain();
}


Net::~Net(void)
{
	callbackMap->release();
}

Net* Net::instance(){
	if(!m_instance){
		m_instance = new Net();
	}
	return m_instance;
}
void Net::sendRequest(const char* url,const char* codeTag ,CCObject* target = NULL,SEL_CallFuncO callback = NULL){
	if(target && callback && !callbackMap->objectForKey(codeTag)){
		CallbackObject* obj = new CallbackObject();
		obj->target = target;
		obj->func = callback;
		callbackMap->setObject(obj,codeTag);
	}
	CCHttpRequest* request = new CCHttpRequest();
	request->setUrl(url);
	request->setRequestType(CCHttpRequest::kHttpGet);
	request->setResponseCallback(this,httpresponse_selector(Net::onHttpRequestCompleted));
	request->setTag(codeTag);
	CCHttpClient::getInstance()->send(request);
	request->release();
}

void Net::onHttpRequestCompleted(CCHttpClient *sender, CCHttpResponse *response){
	
	const char* codeTag = response->getHttpRequest()->getTag();

	int statusCode = response->getResponseCode();
	CCLog("response code: %d", statusCode);

	if (!response->isSucceed()) 
	{
		CCLog("response failed");
		CCLog("error buffer: %s", response->getErrorBuffer());
		return;
	}

	// dump data
	std::vector<char> *buffer = response->getResponseData();
	long bufferSize = buffer->size();
	std::string reslut;
	string temp;
	for (long i = 0; i < bufferSize; i++)
	{
		temp = (*buffer)[i];
		if(temp != "\r" && temp != "\n" && temp != "\t"){
			reslut += temp;
		}
	}
	reslut+="\0";
	CallbackObject* obj = (CallbackObject*)callbackMap->objectForKey(codeTag);
	if(obj){
		CCObject* target = obj->target;
		SEL_CallFuncO func = obj->func;
		(target->*func)(CCString::create(reslut));
	}
}
